<template>
 <!-- 甲供清单 -->
    <div>
        <div class="e-table" style="background-color: #fff" v-if="showTable">
            <!-- 头部buttons -->
            <div class="top" v-if="isAdd">
                <div class="left">
                   <div>
                        <el-button size="small" type="primary" v-if="isBidding" plain class="btn-greenYellow" @click="selectPackage">选择包件</el-button>
                        <el-dropdown style="margin-right:10px" v-else trigger="click" @command="planClick">
                            <el-button type="primary" class="btn-greenYellow">
                                选择计划<i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item
                                    v-for="item in planList"
                                    :key="item.value" :command="item.value"
                                >{{ item.label }}</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                        <el-button size="small" v-if="rescue" type="primary"  plain class="btn-greenYellow" @click="emergencyRescue">应急抢险</el-button>
                    </div>
                </div>
            </div>
            <div>
                <div class="errorMsg" v-if="errorMsg.length>0">
                    <span >
                        {{ errorMsg.join(',') }}
                    </span>
                </div>

                <el-table
                    :data="tableData"
                    ref="tableRef"
                    border
                    style="width: 100%"
                    @cell-mouse-enter="cellMouseEnter"
                    @selection-change="planTableSelect"
                    :row-class-name="tableRowClassName"
                    @cell-mouse-leave="cellMouseLeave"
                    :cell-class-name="cellClsNm"
                    :header-cell-style="{ textAlign: 'center' }"
                    :tree-props="{
                    children: 'children',
                    hasChildren: 'hasChildren',
                    }"
                    row-key="uuid"
                    class="table"
                    :max-height="$store.state.tableHeight"
                    v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'tableRef' }"
                >
                    <el-table-column
                        label="操作"
                        fixed
                        width="100px"
                        align="left"
                        >
                        <template slot-scope="{ row }">
                           <img src="@/assets/btn/delete.png" class="cancel_delete"
                                v-if="isAdd && !row.topClassId"
                                @click="deleteEle(row)"
                                title="删除"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column
                            label="序号"
                            type="index"
                            width="100"
                            align="center"
                        >
                    </el-table-column>
                    <el-table-column
                        prop="planName"
                        label="计划类型"
                        width="150"
                        align="left"
                        v-if="formData.listType === 1"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="planNumber"
                        label="计划编号"
                        min-width="200"
                        align="left"
                        v-if="formData.listType === 1"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="typeName"
                        label="类别"
                        min-width="200"
                        align="left"
                    >
                    <!-- <template slot-scope="{ row }">
                            {{ row.topClassId ? row.typeName : (!row.customId.includes('-') ? row.typeName : '') }}
                        </template> -->
                    </el-table-column>
                    <el-table-column
                        prop="materialName"
                        label="物资名称"
                        min-width="200"
                        align="left"
                    >
                    </el-table-column>
                    <el-table-column prop="specificationModel" label="规格型号" width="100">
                    </el-table-column>
                    <el-table-column prop="unit" label="计量单位" width="100">
                    </el-table-column>
                    <el-table-column prop="textureOfMaterial" label="材质" width="150">
                    <template slot-scope="{ row }">
                        <el-input
                        @input="input(row)"
                        v-model="row.textureOfMaterial"
                        clearable
                        v-if="!row.topClassId && isAdd"
                        ></el-input>
                        <div v-else>{{ row.textureOfMaterial }}</div>
                    </template>
                    </el-table-column>
                    <el-table-column prop="quantity" label="数量"  align="right"  width="120">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.quantity"
                                placeholder="请输入内容"
                                v-if="isEdit && !row.topClassId"
                                v-enterJustFloat2
                               @change="onCalcAmount(row,'quantityUpdateFlag')"
                            ></el-input>
                            <div v-else>{{ row.quantity }}</div>
                            <historyUpdateTable
                                v-if="checkEmpty(row.numberRecords)"
                                @clickIcon="clickIcon(row.numberRecords)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="unitPrice" label="单价(元)" align="right" width="120">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.unitPrice"
                                placeholder="请输入内容"
                                v-if="isEdit && !row.topClassId"
                                v-enterJustFloat
                                @change="onCalcAmount(row,'unitPriceUpdateFlag')"
                            ></el-input>
                            <div v-else>{{ row.unitPrice }}</div>
                            <historyUpdateTable
                                v-if="checkEmpty(row.priceRecords)"
                                @clickIcon="clickIcon(row.priceRecords)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="金额(元)" align="right" width="120">
                        <template slot-scope="{ row }">
                            <div>{{ row.amount }}</div>
                            <historyUpdateTable
                                v-if="checkEmpty(row.amountRecords) && !row.topClassId"
                                @clickIcon="clickIcon(row.amountRecords)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
              </el-table>
            </div>
         </div>
    </div>
</template>
<script>
import { uidBuilder } from '@/api/base/uid.js'
import { getUnit } from '@/api/subcontractApi/currency.js'
import { isFourInput, isNumInput, isTwoInput, isFourInputJust } from '@/utils/rules.js'
import { mapState, mapMutations } from 'vuex'
import { selectDataClient } from '@/utils/common'
import historyUpdateTable from '@/pages/balanceContract/materialContract/ctMaterialPurchase/components/historyUpdateTable.vue'
import fn from '@/utils/checkEmpty.js'
import {  getUuid } from '@/utils/common'
import service from '@/utils/request'
const {  httpGet } = service
export default {
    props: {
        detailsOfProposed: {
            type: Array,
            default: function () {
                return []
            }
        },
        tenderClass: {
            type: String,
            default: ''
        },
        billid: {
            type: String,
            default: ''
        },
        contractListTable: {
            type: Array,
            default: function () {
                return []
            }
        },
        errorMsg: {
            type: Array,
            default: function () {
                return []
            }
        },
        isBidding: {
            type: Boolean,
            default: false
        },
        mainInfo: {
            type: Object,
            default: function () {
                return {}
            }
        },
        formData: {
            type: Object,
            default: function () {
                return {}
            }
        },
        auditState: {
            type: Object,
            default: function () {
                return {
                    canAudit: false,
                    canModify: true,
                    canUndoAudit: false,
                    freeNextUnits: [],
                    isFree: false,
                }
            }
        },
        //是否可以新增
        isAdd: {
            default: true
        },
        //是否可以编辑
        isEdit: {
            default: true
        },
        subcontract: { //接口
        },
        state: { //流程状态
            type: Number
        },
        dtlList: { //包件清单
            type: Array,
            default: function () {
                return []
            }
        },
    },
    model: {
        prop: 'contractListTable',
        event: 'change'
    },

    data () {
        return {
            detailsOfProposedArr: [],
            tableData: [],
            mapTableData: {},
            addList: [], // 缓存新增数据
            unitList: [],
            searchKey: '',
            isSearch: false,
            addFlag: true,
            materialListTeam: [], //存储执行队列
            materialListIndex: 0,
            showTable: true,
            rescue: false, //应急抢险权限
            planList: [
                { value: 1, label: '总计划' },
                { value: 2, label: '零星采购计划' },
                { value: 3, label: '月计划' },
                { value: 4, label: '周材采购计划' },
                { value: 5, label: '周材临时需用计划' },
            ], //1 :'总计划', 2:'零星采购计划', 3:'月计划', 4:'周材采购计划', 5:'临时需用计划'
        }
    },
    created () {
        this.getData()
    },
    mounted () {
        getUnit().then(res=>{
            let arr = res.map(x=>{
                let obj = {
                    value: '',
                    label: '',
                }
                obj.value = x.kvValue
                obj.label = x.kvKey
                return obj
            })
            this.unitList = arr
        })
        if(this.menuid) {
            httpGet({
                url: '/permission/functional/getFunctional',
                params: { menuId: this.menuid }
            }).then(res=>{
                if(res.find(x=>x.functionCode === 'rescue')) {
                    this.rescue = true
                }else{
                    this.rescue = false
                }
            })
        }
    },
    computed: {
        tenderId () {
            return this.$route.query.billid
        },
        ...mapState({
            serverList: state => state.contract.ctClassify.serverList,
            supplyType: state => state.contract.ctClassify.supplyTypeList,
            menuid: state => state.contract.ctClassify.menuid, //当前菜单的menuid
        }),
        //判断数据是否为空
        checkEmpty () {
            return datas=>{
                return !fn.checkEmpty(datas)
            }
        }
    },
    components: {
        historyUpdateTable,
    },
    watch: {
        contractListTable: {
            handler (newName) {
                this.tableData = newName
            },
            immediate: false,
            deep: true
        },
        tableData: {
            handler (newName) {
                this.$emit('change', newName)
            },
            immediate: true,
            deep: true
        },
        dtlList: {
            handler (newName) {
                this.$emit('isMonitorTaxRate')
                const tableData = []
                this.tableData.forEach(item=>{ //将表格数据处理成平级
                    item.children.forEach(x=>{
                        tableData.push(x)
                    })
                })

                const res = []
                newName.forEach(item=>{
                    const obj = tableData.find(x=>x.oriBillId === item.recordId)
                    if(!obj || obj.changeType === -1) {
                        res.push(item)
                    }
                })
                const mapObj = this.mapObj
                let arr = [...this.tableData]
                res.forEach(item => {
                    if(item.freightPrice > 0) { //生产服务清单
                        const obj = {
                            'amount': 0,
                            'billId': '',
                            'changeState': 0,
                            'changeType': 1,
                            'name': '',
                            'oneLevelTypeId': '',
                            'oneLevelTypeName': '',
                            'quantity': item.num,
                            'sourceId': this.billid,
                            'specificationModel': '',
                            'textureOfMaterial': '',
                            'typeId': 1,
                            'typeName': '物流运输',
                            'unit': '',
                            'unitPrice': item.freightPrice,
                            oriUnitPrice: item.freightPrice, //原单价
                            oriQuantity: item.num, //原单价
                            oriBillId: item.recordId, //原id
                        }
                        const serverList = this.serverList
                        serverList.push(obj)
                        this.setServerList(serverList)
                    }
                    const children = []
                    item.materialClassNameArr = item.type.split('/')
                    item.materialClassIdArr = item.materialTypeId.split('/')
                    // TODO: 统计小计
                    let obj
                    const topClassId = item.materialClassIdArr.splice(0, 1).toString()
                    const topClassName = item.materialClassNameArr
                        .splice(0, 1)
                        .toString()
                    if (!mapObj[topClassId] || mapObj[topClassId].changeType === -1) {
                        obj = {
                            topClassId,
                            topClassName,
                            customId: topClassId,
                            typeId: topClassId,
                            typeName: topClassName,
                            uuid: getUuid(),
                            totalAmount: '',
                            totalQuantity: '',
                            sourceId: this.billid
                        }
                        arr.push(obj)
                        mapObj[topClassId] = obj
                    } else {
                        obj = mapObj[topClassId]
                    }
                    // 物资名称
                    children.push({
                        uuid: getUuid(),
                        billId: '',
                        billNo: item.billNo,
                        amount: (parseFloat(item.limitPrice) * parseFloat(item.num)).toFixed(2), //预算金额(元)
                        unitPrice: item.limitPrice, //预算单价(元)
                        changeType: 1,
                        quantity: item.num, //数量
                        dtlId: '', //物资总计划明细id
                        customId: getUuid(),
                        typeId: item.materialClassIdArr.join('/'), //物资类别id(
                        typeName: item.materialClassNameArr.join('/'), //物资类别名称
                        materialId: item.materialNameId, //物资id
                        materialName: item.name, //物资名称
                        planQuantity: 0, //计划数量
                        specificationModel: item.specs, //规格型号
                        textureOfMaterial: item.texture, //材质
                        unit: item.unit, //计量单位
                        sourceId: this.billid, //源单id
                        oriQuantity: item.num, //原数量
                        oriUnitPrice: item.limitPrice, //原单价
                        oriBillId: item.recordId
                    })
                    obj.children = !obj.children
                        ? children
                        : obj.children.concat(children)
                        // 统计小计
                    obj.amount = this.count_(obj)
                    obj.children = this.uniqueArray(obj.children, 'customId')
                })
                this.tableData = arr
                this.$emit('changePlanType', {
                    name: '选择包件',
                    id: 4
                })
            },
            immediate: false,
            deep: true
        }
    },
    methods: {
        ...mapMutations(
            'contract', ['setServerList']
        ),
        ...mapMutations(['setHistoryTableData']),
        ...mapMutations(['setSelectedInfo']),
        // 获取列表数据
        getData () {
            this.showTable = false
            //获取物资清单
            this.subcontract.getMaterialList({
                sourceId: this.billid,
            }).then(res => {
                res = res.code ? [] : res
                this.mapObj = {}
                res.forEach(item=>{
                    item.changeType = 0
                    if(this.state === 1) {
                        item.quantityUpdateFlag = false
                        item.unitPriceUpdateFlag = false
                        item.amountUpdateFlag = false
                    }
                })
                this.tableData = []
                const arr = [...new Set(res.map(x=>x.oneLevelTypeId))]
                arr.forEach(item=>{
                    const children = res.filter(x=>x.oneLevelTypeId === item).map(x=>{
                        x.uuid = getUuid()
                        x.customId = getUuid()
                        return x
                    })
                    const parent = {
                        topClassId: children[0].oneLevelTypeId,
                        topClassName: children[0].oneLevelTypeName,
                        customId: children[0].oneLevelTypeId,
                        typeId: children[0].oneLevelTypeId,
                        typeName: children[0].oneLevelTypeName,
                        uuid: getUuid(),
                        totalAmount: '',
                        totalQuantity: '',
                        sourceId: this.billid,
                        children,
                    }
                    if (!this.mapObj[parent.topClassId]) {
                        this.mapObj[parent.topClassId] = parent
                    }
                    const count = this.count_(parent)
                    parent.amount = count
                    this.tableData.push(parent)
                })
                console.log('tableData', this.tableData)
                this.showTable = true
            })
        },
        // 输入后计划金额
        onCalcAmount (row, feild) {
            this.$emit('isMonitorTaxRate')
            if(this.state === 1) {
                row.amountUpdateFlag = true
                row[feild] = true
            }
            row.amount = row.changeType !== -1 ?  ( parseFloat(row.quantity ? row.quantity : 0) * parseFloat(row.unitPrice ? row.unitPrice : 0) ).toFixed(2)  : 0
            if(row.changeType !== -1) {
                row.changeType = row.changeType === 1 ? 1 : 2
            }
            for(let i = 0 ;i < this.tableData.length;i++) {
                for(let j = 0;j < this.tableData[i].children.length;j++) {
                    if(this.tableData[i].children[j].uuid === row.uuid) {
                        this.tableData[i].amount = this.count_(this.tableData[i])
                        return
                    }
                }
            }
        },
        tableRowClassName ({ row }) {
            if(row.changeType === -1) {
                return `class-${row.uuid} row-hide`

            }else{
                return `class-${row.uuid} row-show`
            }
        },

        async uidBuilder (params) {
            let temp = ''
            await uidBuilder(params).then(res => {
                temp = res.length === 1 ? res[0] : res
            })
            return temp
        },
        // refreshLoadTree (parentId) {
        //     // 根据父级id取出对应节点数据
        //     // const { row, treeNode, resolve } = this.mapTableData[parentId]
        //     let children = this.mapTableData[parentId].children
        //     const tableRef = this.$refs.tableRef
        //     this.$set(tableRef.store.states.lazyTreeNodeMap, parentId, children)
        // },

        isFourInput (event) {
            isFourInput(event)
        },
        isFourInputJust (event) {
            isFourInputJust(event)
        },
        isNumInput (event) {
            isNumInput(event)
        },
        isTwoInput (event) {
            isTwoInput(event)
        },
        //单价类型切换
        unitPriceTypeChange (row) {
            const fn = data=>{
                data.forEach(item=>{
                    item.unitPriceType = row.unitPriceType
                    if(!item.isDetailed) {
                        fn(item.children)
                    }
                    this.mapTableData[row.billid] = row
                })
            }
            if(!row.isDetailed) {
                fn(row)
            }else{
                this.mapTableData[row.billid] = row
            }
        },
        //单价切换
        unitPriceChange (row) {
            row.children.forEach(item=>{
                item.unitPrice = row.unitPrice
                this.mapTableData[item.billid] = item
                this.onCalcAmount(item)
            })
            this.mapTableData[row.billid] = row
        },
        //数量切换
        quantityChange (row) {
            const parent = this.mapTableData[row.parentId]
            // 统计所有同级
            const countSibling = parent.children.reduce((prev, item) => {
                return prev + Math.round(item.changeType !== -1 ? item.quantity : 0)
            }, 0)
            // 赋值汇总数据给父级
            parent.quantity = countSibling // 赋值汇总数据给父级
        },
        clickIcon (list) {
            this.setHistoryTableData(list)
        },

        cellMouseEnter (row) {
            this.MouseEnterId = row.uuid
        },
        //获取计划明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        count_ (obj) {
            return obj.children.reduce((prev, c) => {
                if(c.changeType === -1) {
                    return prev
                }else{
                    prev = (parseFloat(prev) + parseFloat(c.amount) || 0).toFixed(2)
                    return prev
                }
            }, 0)
        },
        //选择计划
        projectPlan (val, index) {
            if(this.formData.listType != 1) {
                this.clearData()
            }
            const tableData = []
            this.tableData.forEach(item=>{ //将表格数据处理成平级
                item.children.forEach(x=>{
                    tableData.push(x)
                })
            })
            const res = []
            val.forEach(item=>{
                const obj = tableData.find(x=>x.oriBillId === item.dtlId)
                if(!obj || obj.changeType === -1) {
                    res.push(item)
                }
            })
            const mapObj = this.mapObj
            res.forEach(item => {
                item.materialClassNameArr = item.materialClassName.split('/')
                item.materialClassIdArr = item.materialClassId.split('/')
                // TODO: 统计小计
                let obj
                const topClassId = item.materialClassIdArr.splice(0, 1).toString()
                const topClassName = item.materialClassNameArr
                    .splice(0, 1)
                    .toString()
                if (!mapObj[topClassId] || mapObj[topClassId].changeType === -1) {
                    obj = {
                        topClassId,
                        topClassName,
                        customId: topClassId,
                        typeId: topClassId,
                        typeName: topClassName,
                        uuid: getUuid(),
                        totalAmount: '',
                        totalQuantity: '',
                        sourceId: this.billid,
                        children: [],
                    }
                    this.tableData.push(obj)
                    mapObj[topClassId] = obj
                } else {
                    obj = mapObj[topClassId]
                }
                // 物资名称
                obj.children.push({
                    uuid: getUuid(),
                    billId: '',
                    billNo: item.billNo,
                    amount: (parseFloat(item.unitPrice ? item.unitPrice : 0) * parseFloat(item.planQuantity ? item.planQuantity : 0)).toFixed(2), //预算金额(元)
                    unitPrice: item.unitPrice, //预算单价(元)
                    changeType: 1,
                    quantity: item.planQuantity, //数量
                    dtlId: '', //物资总计划明细id
                    customId: getUuid(),
                    typeId: item.materialClassIdArr.join('/'), //物资类别id(
                    typeName: item.materialClassNameArr.join('/'), //物资类别名称
                    materialId: item.billId, //物资id
                    materialName: item.materialName, //物资名称
                    planQuantity: item.planQuantity, //计划数量
                    specificationModel: item.spec, //规格型号
                    textureOfMaterial: item.texture, //材质
                    unit: item.unit, //计量单位
                    sourceId: this.billid, //源单id
                    oriBillId: item.dtlId, //原清单id
                    oriQuantity: item.planQuantity, //原数量
                    planId: item.billId, //计划id
                    planName: this.planList.find(x=>x.value === index).label, //计划名称
                    planNumber: item.billNo, //计划编号
                    planType: index, //计划类型
                })
                // 统计小计
                const count = this.count_(obj)
                obj.amount = count
                obj.children = this.uniqueArray(obj.children, 'customId')
            })
            this.$emit('changePlanType', {
                name: '选择计划',
                id: 1
            })
        },
        //选择包件
        selectPackage () {
            const tableData = []
            this.tableData.forEach(item=>{ //将表格数据处理成平级
                item.children.forEach(x=>{
                    tableData.push(x)
                })
            })
            let ids = tableData.filter(x=>(x.oriBillId && x.changeType !== -1)).map(x=>x.oriBillId)
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/tender/materialProvisioning/wpf/dtlList', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: this.mainInfo.secondParty.dtlId,
                Title: '选择包件清单' // 标题
            }).then(val => {
                if(this.formData.listType != 4) {
                    this.clearData()
                }
                const res = []
                val.forEach(item=>{
                    const obj = tableData.find(x=>x.oriBillId === item.recordId)
                    if(!obj || obj.changeType === -1) {
                        res.push(item)
                    }
                })
                const mapObj = this.mapObj
                res.forEach(item => {
                    if(item.freightPrice > 0) { //生产服务清单
                        const obj = {
                            'amount': 0,
                            'billId': '',
                            'changeState': 0,
                            'changeType': 1,
                            'name': '',
                            'oneLevelTypeId': '',
                            'oneLevelTypeName': '',
                            'quantity': item.num,
                            'sourceId': this.billid,
                            'specificationModel': '',
                            'textureOfMaterial': '',
                            'typeId': 1,
                            'typeName': '物流运输',
                            'unit': '',
                            'unitPrice': item.freightPrice,
                            oriUnitPrice: item.freightPrice, //原单价
                            oriQuantity: item.num, //原单价
                            oriBillId: item.recordId, //原id
                        }
                        const serverList = this.serverList
                        serverList.push(obj)
                        this.setServerList(serverList)
                    }
                    item.materialClassNameArr = item.type.split('/')
                    item.materialClassIdArr = item.materialTypeId.split('/')
                    // TODO: 统计小计
                    let obj
                    const topClassId = item.materialClassIdArr.splice(0, 1).toString()
                    const topClassName = item.materialClassNameArr
                        .splice(0, 1)
                        .toString()
                    if (!mapObj[topClassId] || mapObj[topClassId].changeType === -1) {
                        obj = {
                            topClassId,
                            topClassName,
                            customId: topClassId,
                            typeId: topClassId,
                            typeName: topClassName,
                            uuid: getUuid(),
                            totalAmount: '',
                            totalQuantity: '',
                            sourceId: this.billid,
                            children: []
                        }
                        this.tableData.push(obj)
                        mapObj[topClassId] = obj
                    } else {
                        obj = mapObj[topClassId]
                    }
                    // 物资名称
                    obj.children.push({
                        uuid: getUuid(),
                        billId: '',
                        billNo: item.billNo,
                        amount: (parseFloat(item.limitPrice) * parseFloat(item.num)).toFixed(2), //预算金额(元)
                        unitPrice: item.limitPrice, //预算单价(元)
                        changeType: 1,
                        quantity: item.num, //数量
                        dtlId: '', //物资总计划明细id
                        customId: getUuid(),
                        typeId: item.materialClassIdArr.join('/'), //物资类别id(
                        typeName: item.materialClassNameArr.join('/'), //物资类别名称
                        materialId: item.materialNameId, //物资id
                        materialName: item.name, //物资名称
                        planQuantity: 0, //计划数量
                        specificationModel: item.specs, //规格型号
                        textureOfMaterial: item.texture, //材质
                        unit: item.unit, //计量单位
                        sourceId: this.billid, //源单id
                        oriQuantity: item.num, //原数量
                        oriUnitPrice: item.limitPrice, //原单价
                        oriBillId: item.recordId
                    })
                    // 统计小计
                    obj.amount = this.count_(obj)
                    obj.children = this.uniqueArray(obj.children, 'customId')
                    this.$emit('changePlanType', {
                        name: '选择包件',
                        id: 4
                    })
                })
            })

        },
        //应急抢险
        emergencyRescue () {
            selectDataClient({
                SelectServiceToken: '/material/categoryLibrary/queryListByParentClassId2',
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                Title: '物料选择'
            }).then(val => {
                if(this.formData.listType != 2) {
                    this.clearData()
                }
                const mapObj = this.mapObj
                val.forEach(item => {
                    item.materialClassNameArr = item.classNamePath.split('/')
                    item.materialClassIdArr = item.classIdPath.split('/')
                    // TODO: 统计小计
                    let obj
                    const topClassId = item.materialClassIdArr.splice(0, 1).toString()
                    const topClassName = item.materialClassNameArr
                        .splice(0, 1)
                        .toString()
                    if (!mapObj[topClassId] || mapObj[topClassId].changeType === -1) {
                        obj = {
                            topClassId,
                            topClassName,
                            customId: topClassId,
                            typeId: topClassId,
                            typeName: topClassName,
                            uuid: getUuid(),
                            totalAmount: '',
                            totalQuantity: '',
                            sourceId: this.billid,
                            children: [],
                        }
                        this.tableData.push(obj)
                        mapObj[topClassId] = obj
                    } else {
                        obj = mapObj[topClassId]
                    }
                    // 物资名称
                    obj.children.push({
                        uuid: getUuid(),
                        billId: '',
                        billNo: item.billNo,
                        amount: 0, //预算金额(元)
                        unitPrice: 0, //预算单价(元)
                        changeType: 1,
                        quantity: 0, //数量
                        dtlId: '', //物资总计划明细id
                        customId: getUuid(),
                        typeId: item.materialClassIdArr.join('/'), //物资类别id(
                        typeName: item.materialClassNameArr.join('/'), //物资类别名称
                        materialId: item.billId, //物资id
                        materialName: item.materialName, //物资名称
                        planQuantity: 0, //计划数量
                        specificationModel: item.spec, //规格型号
                        textureOfMaterial: '', //材质
                        unit: item.unit, //计量单位
                        sourceId: this.billid, //源单id
                        oriUnitPrice: '', //原单价
                        oriQuantity: '', //原单价
                        oriBillId: item.billId, //原id
                    })
                    // 统计小计
                    obj.amount = this.count_(obj)
                    obj.children = this.uniqueArray(obj.children, 'customId')
                })
                this.$emit('changePlanType', {
                    name: '应急抢险',
                    id: 2
                })
            })
        },
        //明细数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },
        //清除数据
        clearData () {
            this.tableData.forEach(item=>{
                for(let i = 0;i < item.children.length;i++) {
                    if( item.children[i].changeType === 1 ) {
                        item.children.splice(i, 1)
                        i--
                    }else{
                        item.children[i].changeType = -1
                    }
                }
                item.changeType = -1
                this.mapObj = {}
            })
        },
        //删除
        deleteEle (row) {
            this.$emit('isMonitorTaxRate')
            for(let i = 0 ;i < this.tableData.length;i++) {
                for(let j = 0;j < this.tableData[i].children.length;j++) {
                    if(this.tableData[i].children[j].uuid === row.uuid) {
                        const fn = ()=>{
                            const arr =  this.tableData[i].children.filter(x=>x.changeType !== -1)
                            if(arr.length === 0) {
                                this.tableData[i].changeType = -1
                                this.tableData[i].amount = 0
                            }else{
                                this.onCalcAmount(arr[0])
                            }
                        }
                        if( this.tableData[i].children[j].changeType === 1 ) {
                            this.tableData[i].children.splice(j, 1)
                            this.$set(this.$refs.tableRef.store.states.lazyTreeNodeMap, this.tableData[i].uuid, this.tableData[i].children)
                            j--
                            fn()
                        }else{
                            this.clientPop('err', this.oneDeleteListErr, () => {
                                this.tableData[i].children[j].changeType = -1
                                fn()
                            })
                        }
                        return
                    }
                }
            }
        },
        //选择计划点击事件
        planClick (index) {
            this.$emit('isMonitorTaxRate')
            const arr = [1, 2, 5, 3, 4]
            /*
                PlanType2使用备注：
                总计划=1，
                零星采购计划=2，
                周材采购计划=3，
                周材临时需用计划=4，
                月计划=5，
                周材租赁计划=6
            */
            // 弹窗选择数据
            const InitParamsStr = {
                'PlanType2': 1, //计划类型
                'BusinessType': '0', //临时需用计划业务类型（0：自购，1：租赁）
                'IsSignContract': '1', //零星采购计划是否要签合同(0:否;1:是;)
            }
            if(index === 1) {
                InitParamsStr.PurchaseType = '0'//总计划采购类型 0：普通采购，1：集中采购
            }else{
                InitParamsStr.PurchaseType = -1
            }
            InitParamsStr.PlanType2 = arr[index - 1]
            selectDataClient({
                SelectServiceToken: '/common/planSelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify(InitParamsStr),
                Title: '选择计划' // 标题
            }).then(val => {
                const data = val.filter(x=>x.isDetailed === 1)
                this.projectPlan(data, index)
            })

        },
        //改变changeType
        input (row) {
            if(row.changeType !== -1) {
                row.changeType = row.changeType === 1 ? 1 : 2
            }
        },
    }
}
</script>
<style lang='scss' scoped>
    ::v-deep .hide-icon{
        .el-table__expand-icon{
            display: none;
        }
    }
    ::v-deep .el-popover__reference-wrapper{
        display: flex;
        height: 100%;
    }
    .selected{
        color:red;
    }
</style>
